﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.Xml;

using ERPStore.Extensions;

using CloudSoft.Extensions;

namespace ERPStore.Exporter.Providers
{
	public class AchetezFacileExport : ExportBase
	{
		private XDocument m_Document;

		public AchetezFacileExport()
		{
		}

		public override void InitializeSettings(Models.Settings settings)
		{
			settings.AllowMissingDefaultImage = false;
			settings.AllowNotSellable = false;
			settings.AllowNullLongDescription = false;
			settings.AllowNullShortDescription = false;
			settings.AllowStockEmpty = false;
			settings.AllowZeroSalePrice = false;
			settings.FileName = "achetezfacile.xml";
		}

		public override string Name
		{
			get { return "AchetezFacile"; }
		}

		public override string LeadSourceId
		{
			get { return "83897742-794B-46A8-84B9-265E3079CA4A"; }
		}

		public override void CreateDocument()
		{
			m_Document = new XDocument(new XDeclaration("1.0", "UTF-8", null));
			var root = new XElement("produits");
			m_Document.Add(root);
		}

		public override void AddElementToDocument(ERPStore.Models.Product product, ERPStore.Models.ProductStockInfo productStock)
		{
			var categorie = GetDeepCategoryName(product);
			var identifiant_unique = product.Code;
			var titre = (product.PageTitle ?? product.Title).Replace(";", " ");
			var prix = string.Format("{0:F2}", product.BestPrice.ValueWithTax);
			var urlBuilder = new ERPStore.Exporter.ProductUrlBuilder();
			var URL_produit = BuildEncryptedProductUrl(LeadSource, product);
			var URL_image = string.Format("http://{0}{1}", GlobalConfiguration.Configuration.Settings.DefaultUrl, string.Format(product.DefaultImage.Url, 0, 0));
			var frais_de_port = "0";
			var deliveryCountry = GlobalConfiguration.Configuration.Settings.Shipping.DeliveryCountryList.Single(i => i.Country == ERPStore.Models.Country.FRA);
			if (product.BestPrice.Value < deliveryCountry.MinimalFreeOfCarriageAmount)
			{
				frais_de_port = string.Format("{0:F2}", deliveryCountry.ShippingFeeAmount);
			}
			if (product.Shipping.Strategy == ERPStore.Models.FeeTransportStrategy.FixedPrice)
			{
				frais_de_port = ToCurrency(product.Shipping.FixedPrice,true);
			}

			string availability = null;
			if (productStock != null)
			{
				if (productStock.PhysicalStock > 0)
				{
					availability = "En stock : Expédition en 48/72H ouvrable";
				}
				else if (productStock.ProvisionnedQuantity > 0)
				{
					availability = string.Format("En cours d'appro {0} jour(s)", productStock.ProvisionningDaysCount + productStock.DeliveryDaysCount);
				}
				else
				{
					availability = string.Format("sur commande, compter {0} jour(s)", productStock.ProvisionningDaysCount + productStock.DeliveryDaysCount);
				}
			}
			else
			{
				availability = string.Format("sur commande");
			}
			var D3E = (product.RecyclePrice != null) ? ToCurrency(product.RecyclePrice.ValueWithTax,true) : "";
			var marque = (product.Brand != null) ? product.Brand.Name : "";
			var EAN = product.Gtin.EAN;
			string promotionalPrice = null;
			if (product.StrikedPrice != null)
			{
				promotionalPrice = prix;
				prix = string.Format("{0:F2}", product.StrikedPrice.Value);
			}

			if (product.Category == null)
			{
				return;
			}

			var element = new XElement("produit");
			element.Add(new XElement("idproduit", new XCData(product.Id.ToString())));
			element.Add(new XElement("reference", new XCData(product.Code)));
			element.Add(new XElement("ean", new XCData(EAN ?? string.Empty)));
			element.Add(new XElement("nomproduit", new XCData(titre)));
			element.Add(new XElement("categorie", new XCData(product.Category.GetRootProductCategory().Name)));
			element.Add(new XElement("souscategorie", new XCData(product.Category.Name)));
			element.Add(new XElement("prix", new XCData(prix)));
			element.Add(new XElement("disponibilite", new XCData(product.HasStock ? "En Stock" : "Epuisé")));
			element.Add(new XElement("delaiexpedition", new XCData(availability)));
			element.Add(new XElement("fraisdeport", new XCData(frais_de_port)));
			element.Add(new XElement("urlficheproduit", new XCData(URL_produit)));
			element.Add(new XElement("urlimage", new XCData(URL_image)));
			element.Add(new XElement("marque", new XCData(marque ?? string.Empty)));
			element.Add(new XElement("descriptif", new XCData(product.LongDescription ?? product.ShortDescription ?? product.Title)));

			m_Document.Root.Add(element);
		}

		public override void SaveDocument()
		{
			var xmlWriterSettings = new XmlWriterSettings()
			{
				CheckCharacters = false,
				Indent = true,
			};
			var path = Configuration.ConfigurationSettings.AppSettings["exportPath"];
			var fileName = System.IO.Path.Combine(path, Settings.FileName);

			using (var xmlWriter = XmlWriter.Create(fileName, xmlWriterSettings))
			{
				m_Document.Save(xmlWriter);
				xmlWriter.Flush();
				xmlWriter.Close();
			}
		}

		public override void Dispose()
		{
			m_Document = null;
		}

		protected override string GetDeepCategoryName(ERPStore.Models.Product product)
		{
			var path = new List<string>();
			var c = product.Category;
			while (true)
			{
				if (c != null)
				{
					path.Add(c.Name);
				}
				else
				{
					break;
				}
				c = c.Parent;
			}
			if (path.IsNullOrEmpty())
			{
				return string.Empty;
			}

			path.Reverse();
			return path.JoinString(" > ");
		}

	}
}
